package com.example.utils;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.exception.FileNotExistException;
import com.example.exception.exception;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Component
public class FileUtil {

    private final static String uploadPath = "C:/fresh_shop/uploads/";
    private final static String EMPTY_STRING = "";

    public UrlResource getFile(String filename) {
        Path path = Paths.get(uploadPath);
        if (!path.toFile().exists()) {
            throw new FileNotExistException();
        }
        Path filePath = path.resolve(filename).normalize();
        UrlResource resource = null;
        try {
            resource = new UrlResource(filePath.toUri());
        } catch (MalformedURLException e) {
            throw new exception(e);
        }
        if (!resource.exists()) {
            throw new FileNotExistException();
        }
        return resource;
    }

    public String saveImgFile(MultipartFile file) {
        try {
            Path path = Paths.get(uploadPath);
            if (!path.toFile().exists()) {
                boolean mkdirs = path.toFile().mkdirs();
            }
            String uuid = UUID.randomUUID().toString();
            String format = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            if ("png".equals(format) || "jpg".equals(format) || "jpeg".equals(format)) {
                String url = uploadPath + uuid + "." + format;
                file.transferTo(new File(url));
                return uuid + "." + format;
            } else {
                throw new exception(400, "图片格式错误");
            }
        } catch (IOException e) {
            throw new exception(e);
        }
    }

    public void deleteFile(String filename) {
        if (StringUtils.isBlank(filename)) {
            return;
        }
        if (JSONUtil.isTypeJSONArray(filename)) {
            deleteFile(JSONUtil.toList(filename, String.class));
        } else {
            deleteFile(List.of(filename));
        }
    }

    public void deleteFile(List<String> filenames) {
        if (filenames == null || filenames.isEmpty()) {
            return;
        }
        Path path = Paths.get(uploadPath);
        if (path.toFile().exists()) {
            for (String filename : filenames) {
                File file = path.resolve(filename).toFile();
                if (file.exists() && file.isFile()) {
                    boolean delete = file.delete();
                }
            }
        }
    }

    public String saveImgFiles(MultipartFile[] motelImages) {
        JSONArray jsonArray = new JSONArray();
        for (MultipartFile motelImage : motelImages) {
            jsonArray.add(this.saveImgFile(motelImage));
        }
        return jsonArray.toString();
    }

    public String saveFile(String base64) {
        String[] split = base64.split(";base64,");
        String format = "png";
        String data = base64;
        if (split.length == 2) {
            format = StringUtils.substringAfterLast(split[0], "/");
            data = split[1];
        }
        String name = UUID.randomUUID() + "." + format;
        File directory = Paths.get(uploadPath).toFile();
        if (!directory.exists()) {
            boolean mkdirs = directory.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(new File(directory, name))) {
            fos.write(Base64.getDecoder().decode(data));
            fos.flush();
            return name;
        } catch (Exception e) {
            throw new exception(e);
        }
    }

    public String readImage2Base64(String avatar) {

        if (StringUtils.isBlank(avatar)) {
            return EMPTY_STRING;
        }
        Path path = Paths.get(uploadPath);
        if (!path.toFile().exists()) {
            return EMPTY_STRING;
        }
        Path filePath = path.resolve(avatar).normalize();
        if (!filePath.toFile().exists()) {
            return EMPTY_STRING;
        }
        String format = StringUtils.substringAfterLast(avatar, ".");
        try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
            String data = Base64.getEncoder().encodeToString(fis.readAllBytes());
            return "data:image/" + format + ";base64," + data;
        } catch (IOException e) {
            throw new exception(e);
        }
    }
}
